package com.dycc.attch_componet.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.dycc.attch_componet.R;
import com.dycc.attch_componet.view.impl.PhotoShowActivity;
import com.dycc.libary.http.commonbean.attach.PicBean;
import com.dycc.libary.view.phoneview.PhotoView;

import java.util.List;

/**
 * Created by wxk on 2018/1/23 0023.
 */

public class PicShowAdapter extends PagerAdapter {

    private List<PicBean> images;
    private Context context;
    private LayoutInflater inflater;

    public PicShowAdapter(List<PicBean> images, Context mcontext) {
        this.images = images;
        this.context = mcontext;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return (images != null) ? images.size() : 0;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        String url = "";
        try {
            url = images.get(position).getUrl();
        } catch (Exception ex) {
        }

        PhotoView photoView = new PhotoView(context);
        if (android.os.Build.VERSION.SDK_INT > 20) {
            photoView.setTransitionName(PhotoShowActivity.SHOWATTACH);
        }
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        photoView.setLayoutParams(layoutParams);
        if (url != null) {
            int index = url.lastIndexOf(".");
            String formatNext;
            if (index == -1) {
                formatNext = "";
            } else {
                formatNext = url.substring(index + 1).toLowerCase();
            }
            if (formatNext.equals("gif")) {
                Glide.with(context).load(url)
                        .asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .placeholder(R.drawable.pic_defaultholder)
                        .into(photoView);
            } else {
                Glide.with(context).load(url)
                        .placeholder(R.drawable.pic_defaultholder)
                        .into(photoView);
            }
            photoView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        }
        container.addView(photoView);
        return photoView;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }
}
